<?php

/**
 * @desc 请求ERP
 * @author zhangweifeng@shopex.cn 15-7-7 上午11:02
 */
class abiapi_erp_rpc {

    private $_api_url = '';
    private $_flag = '';  // erp 标识
    private $_token = '';  // erp 私钥
    private $_timeout = 10;
    public $task_name = '';

    /**
     * @desc 模拟请求api数据
     * @author zhangweifeng@shopex.cn 15-6-19 下午4:21
     * 
     * 调用方式: 
     * $erp_caller_obj = kernel::service('abiapi.rpc_erp_request');
     * if ($erp_caller_obj && method_exists($erp_caller_obj, 'xxx')) {
     *      $caller_result = $erp_caller_obj->xxx();
     * }
     */
    public function erp_caller($request_data, $rpc_id = '') {
        $params = $request_data;
        $abi_globalconf = app::get('site')->getConf('abi_globalconf');
        if (empty($abi_globalconf['abi_erpapi']['url']) || empty($abi_globalconf['abi_erpapi']['flag']) || empty($abi_globalconf['abi_erpapi']['token'])) {
            return json_encode(array('msg' => "请先在 百威管理-》全局配置 里进行配置！"));
        }
        $this->_api_url = $abi_globalconf['abi_erpapi']['url'];
        $this->_flag = $abi_globalconf['abi_erpapi']['flag'];
        $this->_token = $abi_globalconf['abi_erpapi']['token'];

        $sys_data = array(
            'ver' => 1,
            'type' => 'json', //可选
            'charset' => 'utf-8',
            'timestamp' => time()
        );

        $request_data = array_merge($request_data, $sys_data);
        $request_data['flag'] = $this->_flag;
        $request_data['sign'] = $this->gen_sign($request_data, $this->_token);

        $res = $this->_http_post($this->_api_url, $request_data, $params, $rpc_id);
        
        return $res;
    }

    /**
     * @desc 生成签名
     * @param type $params
     * @param type $token
     * @return boolean
     */
    private function gen_sign($params, $token) {
        if (!$token) {
            return false;
        }
        return strtoupper(md5(strtoupper(md5($this->assemble($params))) . $token));
    }

    private function assemble($params) {
        if (!is_array($params)) {
            return null;
        }
        ksort($params, SORT_STRING);
        $sign = '';
        foreach ($params AS $key => $val) {
            if (is_null($val)) {
                continue;
            }
            if (is_bool($val)) {
                $val = ($val) ? 1 : 0;
            }
            $sign .= $key . (is_array($val) ? $this->assemble($val) : $val);
        }
        return $sign;
    }

    /**
     * @desc http 进行api  请求
     * @param type $url 请求地址
     * @param type $request_data 请求的参数
     * @param type $params 应用级参数
     * @return boolean
     */
    private function _http_post($url, $request_data, $params, $rpc_id) {
        $api_log = kernel::single('abiapilog_logging'); // 记录日志
        $api_log->task_name = $this->task_name;
        $rpc_id = $api_log->request_log($request_data['method'], $params, $rpc_id);
        $http = kernel::single('base_httpclient');
        $response = $http->set_timeout($this->_timeout)->post($url, $request_data);

        if ($response === HTTP_TIME_OUT) {
            $api_log->update(array('status' => 'fail', 'msg' => '请求超时'), $rpc_id);
            return false;
        } else {
            $res_result = json_decode($response, 1);
            if (!empty($res_result['error_response'])) {
                $api_log->update(array('status' => 'fail', 'msg' => $res_result['error_response']['msg'] . ' ; ' . $res_result['error_response']['sub_msg']), $rpc_id);
            } else {
                $api_log->update(array('status' => 'success', 'response_json' => $response), $rpc_id);
            }
        }

        return $response;
    }
    
    /**
     * 超时时间设置
     */
    public function set_timeout($timeout) {
        $this->_timeout=$timeout;
    }

}
